/*
 * Copyright 2015-2018 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.naja.auth2server.security;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.MissingNode;
import com.naja.auth2server.entity.User;

import java.io.IOException;
import java.util.Date;

class UserDeserializer extends JsonDeserializer<User> {

	@Override
	public User deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
		ObjectMapper mapper = (ObjectMapper) jp.getCodec();
		JsonNode jsonNode = mapper.readTree(jp);

		long id = readJsonNode(jsonNode, "id").asLong();
		String userName = readJsonNode(jsonNode, "userName").asText();
		String mobile = readJsonNode(jsonNode, "mobile").asText();
		String email = readJsonNode(jsonNode, "email").asText();
		String nickName = readJsonNode(jsonNode, "nickName").asText();
		String password = readJsonNode(jsonNode, "password").asText();
		String avatarUrl = readJsonNode(jsonNode, "avatarUrl").asText();
		Byte certificated  = mapper.convertValue(jsonNode.get("certificated"), Byte.class);
		Date createTime = mapper.convertValue(jsonNode.get("createTime"), Date.class);
		Date updateTime = mapper.convertValue(jsonNode.get("updateTime"), Date.class);
		Date loginTime = mapper.convertValue(jsonNode.get("loginTime"), Date.class);

		User result = new User();
		result.setId(id);
		result.setUserName(userName);
		result.setMobile(mobile);
		result.setEmail(email);
		result.setNickName(nickName);
		result.setPassword(password);
		result.setAvatarUrl(avatarUrl);
		result.setCreateTime(createTime);
		result.setUpdateTime(updateTime);
		result.setLoginTime(loginTime);
		result.setCertificated(certificated);
		return result;
	}
	private JsonNode readJsonNode(JsonNode jsonNode, String field) {
		return jsonNode.has(field) ? jsonNode.get(field) : MissingNode.getInstance();
	}
}
